//
//  Created by Lee on 15/7/28.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "LEUnitView.h"

#define defaultWidth self.frame.size.height // 每一个unitCell的宽度
#define defaultPace   8       // unitCell之间的间距
#define duration      0.5     // 动画执行时间
#define defaultVisibleCount 4 //默认显示的unitCell的个数

@interface LEUnitView ()<LEUnitCellDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView   *scrollView;//显示成员

@property (nonatomic, strong) NSMutableArray *unitList;//用于管理成员

@property (nonatomic, strong) LEUnitCell *defaultUnit;//默认显示的占位图

@property (nonatomic, assign) BOOL hasDelete;//判断是否有删除操作

@property (nonatomic, assign) BOOL frontMove;//判断删除操作unitCell的移动方向

@property (nonatomic, assign) int moveCount;//统计删除操作总共移动的次数

@property (nonatomic, copy) AddBlock addBlock;
@property(nonatomic, copy) LECellClick cellClickBlock;

@property (nonatomic, strong) LEUnitCell *sessionCell;//缓存cell，用于删除

@property (nonatomic, strong) NSLock *lock;

@end

@implementation LEUnitView

- (void)setSessionCell:(LEUnitCell *)sessionCell {
    if (!_sessionCell) {
        _sessionCell = sessionCell;
    }
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self setProperty];
        
        self.lock = [[NSLock alloc] init];
        self.lock.name = @"CYDeleteLockName";
    }
    return self;
}
/*
 *   @method
 *   @function
 *   初始化_scrollView等
 */
- (void) setProperty {
    _unitList = [[NSMutableArray alloc] init];
    _hasDelete = NO;
    _moveCount = 0;
    
    _scrollView = [[UIScrollView alloc] init];
    _scrollView.delegate = self;
    _scrollView.frame = self.frame;
    _scrollView.backgroundColor = [UIColor clearColor];
    _scrollView.scrollEnabled = YES;
    _scrollView.directionalLockEnabled = YES;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.alwaysBounceHorizontal = YES;
    _scrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault;
    _scrollView.contentSize = [self contentSizeForUIScrollView:0];
    [self addSubview:_scrollView];
    [_scrollView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero];

    _defaultUnit = [[LEUnitCell alloc] initWithFrame:CGRectMake(defaultPace, 0, defaultWidth+20, defaultWidth) andIconImage:[UIImage imageNamed:@"icon_btn_add_unpressed"] andName:DEFAULTCELL];
    [_scrollView addSubview:_defaultUnit];
    [_defaultUnit addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addUnitCell:)]];
    
    [self scrollViewAbleScroll];
}

- (void)addUnitCell:(UITapGestureRecognizer *)tap {
    if (self.addBlock) {
        _addBlock();
    }
}

- (void)addButtonClick:(AddBlock)block {
    self.addBlock = block;
}
/**
 *  cell点击，若不调用该方法，默认为删除cell
 *
 *  @param cellClickBlock
 */
- (void)cellClick:(LECellClick)cellClickBlock {
    self.cellClickBlock = [cellClickBlock copy];
}

#pragma mark - deleteCell
/**
 *  删除cell
 */
- (void)deleteLastCell {
    [self.lock lock];
    [self delete];
    [self.lock unlock];
}

- (void)delete {
    if (self.sessionCell) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1000 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                [self deleteCell:self.sessionCell];
                _sessionCell = nil;
            });
        });
    } else if (self.unitList && self.unitList.count) {
        _sessionCell = self.unitList.lastObject;
        [self delete];
        
    }
}
#pragma mark -
/*
 *  @method
 *  @function
 *  根据index获取UIScrollView的ContentSize
 */
- (CGSize)contentSizeForUIScrollView:(long)index {
    float width = (defaultPace + defaultWidth) * index;
    if (width < _scrollView.bounds.size.width)
        width = _scrollView.bounds.size.width;
    return CGSizeMake(width, defaultWidth);
}
/*
 *  @method
 *  @function
 *  根据_unitList.count
 *  设置scrollView是否可以滚动
 *  设置scrollView的ContentSize
 *  设置scrollView的VisibleRect
 */
- (void)scrollViewAbleScroll {
//    _scrollView.scrollEnabled = (((_unitList.count + 1) * (defaultPace + defaultWidth)) > _scrollView.frame.size.width) ? YES : NO;
      _scrollView.contentSize = [self contentSizeForUIScrollView:(_unitList.count + 1)];
      [_scrollView scrollRectToVisible:CGRectMake(_scrollView.contentSize.width - defaultWidth, 0, defaultWidth, self.frame.size.height) animated:YES];
}
/*
 *  @method
 *  @function
 *  新增一个unitCell
 *  _defaultUnit向后移动并伴随动画效果
 *  newUnitCell渐变显示
 */
- (LEUnitCell *) addNewUnit:(UIImage *)iconImage withName:(NSString *)name {
    __block LEUnitCell *newUnitCell;
    CGFloat x = (_unitList.count) * (defaultPace + defaultWidth) + defaultPace;
    CYLog(@"%f", defaultWidth);
    newUnitCell = [[LEUnitCell alloc] initWithFrame:CGRectMake(x, 0, defaultWidth, defaultWidth) andIconImage:iconImage andName:name];
    newUnitCell.alpha = 0.1;
    newUnitCell.delegate = self;
    [_unitList addObject:newUnitCell];
    [_scrollView addSubview:newUnitCell];
    [self scrollViewAbleScroll];
    _defaultUnit.alpha = 0.5;

    [UIView animateWithDuration:duration animations:^(){
        CGRect rect = _defaultUnit.frame;
        rect.origin.x += (defaultPace + defaultWidth);
        _defaultUnit.frame = rect;
        _defaultUnit.alpha = 1.0;
        newUnitCell.alpha = 0.8;

    } completion:^(BOOL finished){
        newUnitCell.alpha = 1.0;

    }];
    self.sessionCell = newUnitCell;
    return newUnitCell;
}
/*
 *  @method
 *  @function
 *  unitCell被点击代理，需要执行删除操作
 */
- (void)unitCellTouched:(LEUnitCell *)unitCell {
    if (self.cellClickBlock) {
        self.cellClickBlock(self, unitCell);
    } else {
        [self deleteCell:unitCell];
    }
}
/**
 *  删除cell
 */
- (void)deleteCell:(LEUnitCell *)unitCell {
    _hasDelete = YES;
    int index = (int)[_unitList indexOfObject:unitCell];
    
    // step_1: 设置相关unitCell的透明度
    unitCell.alpha = 0.8;
    
    // 判断其余cell的移动方向（从前向后移动/从后向前移动）
    _frontMove = NO;
    if (_unitList.count - 1 > defaultVisibleCount
        && (_unitList.count - index - 1) <= defaultVisibleCount) {
        _frontMove = YES;
    }
    if (index == _unitList.count - 1 && !_frontMove)
        _defaultUnit.alpha = 0.5;
    
    [UIView animateWithDuration:duration animations:^(){
        
        // step_2: 其余unitCell依次移动
        if (_frontMove)
        {
            // 前面的向后移动
            for (int i = 0; i < index; i++) {
                LEUnitCell *cell = [_unitList objectAtIndex:(NSUInteger) i];
                CGRect rect = cell.frame;
                rect.origin.x += (defaultPace + defaultWidth);
                cell.frame = rect;
            }
            _moveCount++;
        }
        else
        {
            // 后面的向前移动
            for (int i = index + 1; i < _unitList.count; i++) {
                LEUnitCell *cell = [_unitList objectAtIndex:(NSUInteger)i];
                CGRect rect = cell.frame;
                rect.origin.x -= (defaultPace + defaultWidth);
                cell.frame = rect;
            }
            
            // step_3: _defaultUnit向前移动
            CGRect rect = _defaultUnit.frame;
            rect.origin.x -= (defaultPace + defaultWidth);
            _defaultUnit.frame = rect;
            _defaultUnit.alpha = 1.0;
            
        }
        unitCell.alpha = 0.0;
        
    } completion:^(BOOL finished){
        
        // step_4: 删除被点击的unitCell
        [unitCell removeFromSuperview];
        [_unitList removeObject:unitCell];
        
        if (_unitList.count <= defaultVisibleCount)
            [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
        if (_frontMove) {
            [self isNeedResetFrame];
        }
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    [self isNeedResetFrame];
}
/*
 *  @method
 *  @function
 *  当删除操作是前面的unitCell向后移动时
 *  做滚动操作或者添加操作需要重新设置每个unitCell的frame
 */
- (void)isNeedResetFrame {
    if (_frontMove && _moveCount > 0) {

        for (int i = 0; i < _unitList.count; i++) {
            LEUnitCell *cell = [_unitList objectAtIndex:(NSUInteger) i];
            CGRect rect = cell.frame;
            rect.origin.x -= (defaultPace + defaultWidth) * _moveCount;
            cell.frame = rect;
        }

        CGRect rect = _defaultUnit.frame;
        rect.origin.x -= (defaultPace + defaultWidth) * _moveCount;
        _defaultUnit.frame = rect;

        _frontMove = NO;
        _moveCount = 0;
    }

    if (_hasDelete) {
        _scrollView.contentSize = [self contentSizeForUIScrollView:(_unitList.count + 1)];
        _hasDelete = !_hasDelete;
    }
}

- (void)dismission {
    self.cellClickBlock = nil;
    self.addBlock = nil;
}

- (void)dealloc {
    CYLog(@"UnitView销毁");
    self.cellClickBlock = nil;
    self.addBlock = nil;
}
@end
